﻿<?php
/**
* 功能: 内存缓存操作类，包括使用MEMECACHED和MEMCACHE
* 创建日期: 2010-09-25
* 最后更新: 2010-09-25
* 作者: slash
*/
class CacheTt
{
	/**
	 * 扩展连接句柄
	 */
	var $_conn;

	var $prefix;  //前缀
	/**
	 * 使用缓存的扩展类型
	 * pecl-memcache 和 pecl-memcached 两种扩展
	 * @var string
	 */
	var $_extension_type;

	

	/**
	 * 默认缓存策略，用于分布式
	 * servers 缓存服务器组
	 * life_time 过期时间
	 * compressed	是否压缩缓存数据
	 * persistent	是否打开持久连接
	 *
	 * @var array
	 */
	protected $_default_config = array(
		'servers'	=> array(),
		'life_time'     => 0,
    'compressed'    => false,
    'persistent'    => true,
	);

	/**
	 * 构造函数
	 */
	public function __construct()
	{
		
	}
	/**
	*初始化系统设置
	*	$configs=  array(
	*	'servers'	=> array(
	*		array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 100), //第一组服务器
	*	),
	*	'life_time'     => 0,
  *      'compressed'    => false,
  *      'persistent'    => true,);
	*/
	public function setConnects($configs)
	{
		/**
		 * 这里的配置导入方法可以根据自己的需求进行修改，也可以通过构造函数传参。。
		 * 完全可以根据自己的需求进行定制。
		 */
		$configMemcache['servers'] = $configs;
		//合并缓存策略
		$configMemcache = array_merge($this->_default_config, $configMemcache);
		//如果服务器组为空，则默认为本机的配置
		if (empty($configMemcache['servers']))
		{
			//$configMemcache['servers'][] = $this->_default_server;
			return false;
		}
		$this->_default_config = $configMemcache;
		/**
		 * 判断扩展是否加载，优先级为pecl-memcached
		 */
		if (extension_loaded('memcached'))
		{
			$this->_extension_type = 'pecl-memcached';
			$this->_initMemcached();
		}
		else if (extension_loaded('memcache'))
		{
			$this->_extension_type = 'pecl-memcache';
			$this->_initMemcache();
		}
		else
		{
			die('not extension pecl_memcached or pecl_memcache');
		}
	}
	/**
	 * 初始化pecl-memcached扩展
	 *
	 * @access protected
	 */
	protected function _initMemcached()
	{
		$conn = new Memcached();
		//设置是否压缩缓存数据
        $conn->setOption(Memcached::OPT_COMPRESSION, (boolean)$this->_default_config['compressed']);

		foreach ($this->_default_config['servers'] as $key => $server)
		{
			if (empty($server['weight'])) $server['weight'] = 100;
			if (!$conn->addServer($server['host'], $server['port'], $server['weight']))
			{
                 echo "faie connect memcached server $server[host]:$server[port]";
            }
		}
        $this->_conn = $conn;
	}
	/**
	 * 初始化pecl-memcache扩展
	 *
	 * @access protected
	 */
	protected function _initMemcache()
	{
		$conn = new Memcache();

		foreach ($this->_default_config['servers'] as $key => $server)
		{
			if (empty($server['weight'])) $server['weight'] = 100;
			if (!$conn->addServer($server['host'], $server['port'], $this->_default_config['persistent'], $server['weight']))
			{
                echo "faie connect memcache server $server[host]:$server[port]";
            }
		}
        $this->_conn = $conn;
	}
	/**
	*设置前缀
	*
	*
	*/
		public function init($type){
			$this->prefix = $type;
	}
	/**
	  * 写入缓存
     * [code]
     * $memcache->set('key', 'value', 3600);
     * $memcache->set('key', 'value', array('life_time' => 3600, 'compressed' => true));
     * $memcache->set(array('key1' => 'value1', 'key2' => 'value2'), 3600);
     * $memcache->set(array('key1' => 'value1', 'key2' => 'value2'), array('life_time' => 3600, 'compressed' => true));
     * [/code]
	 */
	public function setValue()
	{
		$argsArr = func_get_args();
		$params = array();
		/**
		 * 组合参数
		 */
		if (is_array($argsArr[0]))
		{
			$params[] = $argsArr[0];
            if (isset($argsArr[1]))
            {
                if (is_array($argsArr[1]))
                {
                    $params[] = $argsArr[1];
                }
                elseif (is_numeric($argsArr[1]))
                {
                    $params[] = array('life_time' => $argsArr[1]);
                }
            }
		}
		//else if (is_string($argsArr[0]) && isset($argsArr[1]))
		else if (intval($argsArr[0]) > 0 && isset($argsArr[1]))
		{
			$params[] = array($argsArr[0] => $argsArr[1]);
            if (isset($argsArr[2]))
            {
                if (is_array($argsArr[2]))
                {
                    $params[] = $argsArr[2];
                }
                elseif (is_numeric($argsArr[2]))
                {
                    $params[] = array('life_time' => $argsArr[2]);
                }
            }
		}
		else
		{
			return false;
		}
		
		if ($this->_extension_type === 'pecl-memcached')
		{
            return call_user_func_array(array($this, '_setMemcached'), $params);
        }
        else
        {
            return call_user_func_array(array($this, '_setMemcache'), $params);
        }
	}
	/**
     * 写入缓存，使用pecl-memcached
     *
     * @param array $set
     * @param array $config
     * @access protected
     * @return boolean
     */
	protected function _setMemcached(array $set, array $config = array())
	{
		//print_r($set);
		$life_time = isset($config['life_time']) ? $config['life_time'] : $this->_default_config['life_time'];
        $expire_time = time() + $life_time;
        return $this->_conn->setMulti($set, $expire_time);
	}
	/**
     * 写入缓存，使用pecl-memcache
     *
     * @param array $set
     * @param array $config
     * @access protected
     * @return boolean
     */
	protected function _setMemcache(array $set, array $config = array())
	{
		$compressed = isset($config['compressed']) ? $config['compressed'] : $this->_default_config['compressed'];
        $life_time = isset($config['life_time']) ? $config['life_time'] : $this->_default_config['life_time'];

        while (list($key, $value) = each($set))
        {
            if (!$this->_conn->set($key, $value, $compressed ? MEMCACHE_COMPRESSED : 0, $life_time)) return false;
        }
        return true;
	}
 	/**
     * 读取缓存
     * [code]
     * $memcache->get('key');
     * $memcache->get(array('key1', 'key2'));
     * [/code]
     *
     * @access public
     * @return void
     */
    public function getValue($keys)
    {
        if ($this->_extension_type === 'pecl-memcached')
        {
            return call_user_func_array(array($this, '_getMemcached'), array($keys));
        }
        else
        {
            return call_user_func_array(array($this, '_getMemcache'), array($keys));
        }
    }
    /**
     * 读取缓存，使用pecl-memcache
     *
     * @param mixed $keys
     * @access protected
     * @return mixed
     */
    protected function _getMemcache($keys)
    {
        return $this->_conn->get($keys);
    }
    /**
     * 读取缓存，使用pecl-memcached
     *
     * @param mixed $keys
     * @access protected
     * @return mixed
     */
    protected function _getMemcached($keys)
    {
    	//print_r($keys);
        if (is_array($keys))
        {
            $array = $this->_conn->getMulti($keys);
        }
        else
        {
            $array = $this->_conn->get($keys);
        }
        //print_r($array);
        return unserialize($array);
    }
 	/**
     * 删除缓存
     * [code]
     * $memcache->remove('key');
     * $memcache->remove(array('key1', 'key2'));
     * [/code]
     *
     * @access public
     * @return void
     */
    public function delValue($keys)
    {
        if (is_array($keys))
        {
            while (list(, $key) = each($keys))
            {
                $this->remove($key);
            }
        }
        else
        {
            $this->_conn->delete($keys);
        }
    }
    /**
     * 清除所有缓存
     *
     * @access public
     * @return boolean
     */
    public function clean()
    {
        return $this->_conn->flush();
    }
    /**
     * 获得连接句柄
     *
     * @access public
     * @return object
     */
    public function getHandle() {
        return $this->_conn;
    }
}
/**
$mem = new MemcachedBase;
	
	$configs=  array(
		'servers'	=> array(
			array('host' => '192.168.1.89', 'port' => 20003, 'weight' => 100), //第一组服务器
		),
		'life_time'     => 900,
        'compressed'    => false,
        'persistent'    => true,
);
$mem->setConnects($configs);
$mem->init('tt');
if(!$mem->get('tttest2'))
	{
	array('test'=>'123','test1'=>'222')
	if($mem->set('test2',time())){
		echo "设置成功";
	}else{
		echo "色绘制失败";
	}
	echo $mem->get('test2');
}
echo "1111";
echo "\n";
echo $mem->get('test2');
**/
?>
